package com.cans.lightning.business.system.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);

    public static String viewPicture(OutputStream outputStream, String filePath) {

        String fileName = filePath.substring(filePath.lastIndexOf(".") + 1);
        File file = new File( filePath);
        try {

            if (file.exists() && file.isFile()) {
                //读取图片文件流
                BufferedImage image = ImageIO.read(new FileInputStream(file));
                //将图片写到输出流
                ImageIO.write(image, fileName, outputStream);
                return null;
            } else {
                return "文件不存在";
            }

        } catch (IOException e) {
            return "预览失败";
        }
    }

    public static void viewPicture(OutputStream outputStream,String fileType,  byte[] data) throws IOException {

        try {
            if (data != null) {
                outputStream.write(data);
            } else {
                logger.error("文件不存在");
            }

        } catch (IOException e) {
            logger.error("图片预览失败",e);
        }finally {
            outputStream.close();
        }
    }
}
